package com.omega.framework.common.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Pattern;

/**
 * sql校验
 *
 * @author Lv.
 * @date 2023/8/29 17:12
 */
public class SQLInjectionUtils {
    private static final Logger log = LoggerFactory.getLogger(SQLInjectionUtils.class);

    public static final String FIELD_CHECK_WORDS = ".*(\\*|or\\s|drop\\s|delete\\s|update\\s|truncate\\s|declare\\s|union\\s|'|#|\\-\\-).*";
    public static final String VALUE_CHECK_WORDS = ".*(\\*|'|#|\\-\\-).*";
    private static final Pattern FIELD_PATTERN = Pattern.compile(FIELD_CHECK_WORDS, Pattern.CASE_INSENSITIVE);
    private static final Pattern VALUE_PATTERN = Pattern.compile(VALUE_CHECK_WORDS);

    public static boolean isFieldSafe(String str) {
        if (str == null || str.isEmpty()) {
            return true;
        }
        return !FIELD_PATTERN.matcher(str).matches();
    }

    public static boolean isFieldValueSafe(String str) {
        if (str == null || str.isEmpty()) {
            return true;
        }
        return !VALUE_PATTERN.matcher(str).matches();
    }

    public static void checkFieldSqlInjection(String str, String methodName) {
        try {
            if (!isFieldSafe(str)) {
                FmkLogUtils.info(log, "checkFieldSqlInjection", "{} 发现sql注入敏感字符, 字符串: {}", methodName, str);
            }
        } catch (Throwable ignore) {
        }
    }

    public static void checkFieldValueSqlInjection(String str, String methodName) {
        try {
            if (!isFieldValueSafe(str)) {
                FmkLogUtils.info(log, "checkFieldValueSqlInjection", "{} 发现sql注入敏感字符, 字符串: {}", methodName, str);
            }
        } catch (Throwable ignore) {
        }
    }

    public static void main(String[] args) {
        checkFieldSqlInjection("drop table group_membership; ", "main");
        checkFieldSqlInjection(" table #11 group_membership;", "main");
        checkFieldSqlInjection(" table --11 group_membership;", "main");
        checkFieldSqlInjection("table union select table group_membership;", "main");
        checkFieldSqlInjection("union select table group_membership;", "main");
        checkFieldSqlInjection("droptable group_membership", "main");
    }

}
